##Replication code for "drivers of resemblance: explaining the conversion of pre-electoral coalitions
##into coalition cabinets"
library(QCA)
library(tidyverse)
library(ragg)
library(SetMethods)
library(showtext)

##Consistency Threshold of 0.85----
rob_sec_fif <- read.csv("dpr.csv", sep=";") %>%
               filter(type != "electoral") %>%
               select(-type, -legislative_type, -inter_party_primaries,
                      -low_chamber, -upp_chamber, -status)

rob_sec1 <- rob_sec_fif %>%
            column_to_rownames(var = "cases")

rob_sec2 <- rob_sec1 %>%
            mutate(lwpol = calibrate(lwpol, type = "fuzzy", method = "direct", threshold = "e=3, c=2, i=1")) %>%
            mutate(hlpol = calibrate(hlpol, type = "fuzzy", method = "direct", threshold = "e=1.5, c=2.7, i=4")) %>%
            mutate(htemp = calibrate(htemp, type = "fuzzy", method = "direct", threshold = "e=85, c=70, i=55")) %>%
            mutate(lplp = calibrate(lplp, type = "fuzzy", method = "direct", threshold = "e=0.5, c=0.405, i=0.3")) %>%
            rename(LWPOL = lwpol,
                   MAJ = maj, 
                   HLPOL = hlpol,
                   HTEMP = htemp,
                   LPP = lplp,
                   CR = cr)

##Analysis of Sufficiency
TTsec1 <- truthTable(rob_sec2, outcome = "CR", conditions = c("MAJ", "LWPOL", "HLPOL", "HTEMP", "LPP"),
                     complete = TRUE, incl.cut = 0.85,
                     sort.by = "incl, n+",
                     show.cases = TRUE)

ESA <- findRows("~MAJ*~HTEMP", obj = TTsec1)

##The code below produces Table A.14 in the Supplementary Material
intermediate_result <- minimize(TTsec1, include = "?", details = TRUE, dir.exp = "1,1,1,1,1")

stargazerSol(intermediate_result, 
             outcome = "CR",
             show.cases = T,
             type = "latex")

##Consistency Threshold of 0.90----
TTsec1 <- truthTable(rob_sec2, outcome = "CR", conditions = c("MAJ", "LWPOL", "HLPOL", "HTEMP", "LPP"),
                     complete = TRUE, incl.cut = 0.9,
                     sort.by = "incl, n+",
                     show.cases = TRUE)

##The code below produces Table A.15 in the Supplementary Material
intermediate_result <- minimize(TTsec1, include = "?", details = TRUE, dir.exp = "1,1,1,1,1")

stargazerSol(intermediate_result, 
             outcome = "CR",
             show.cases = T,
             type = "latex")